const axios = require('axios');
const { zhanfuConfig } = require('../config/zhanfuAiApiUrl');
const md5 = require('md5');

function ruxOpenApi(params, api = 'rux.open.auth.token.create', headers = {}) {
  return new Promise((resolve, reject) => {
    try {

      params.timestamp = Math.floor(Date.now() / 1000);
      params.app_key = zhanfuConfig.app.app_key;
      params.api = api;
      const sign = createSign(params);
      // 生成签名
      let strParam = createStrParam(params);

      strParam += `sign=${sign}`;
      headers['Content-Type'] = 'application/json;charset=UTF-8';
      axios({
        method: 'post',
        url: `${zhanfuConfig.app.open_url}?${strParam}`,
        headers,
        timeout: 100000
      }).then(res => {
        resolve(res.data)
      }).catch(err => {
        console.log('err', err)
        reject(err.data)
      })
    } catch (error) {
      reject(error)
    }
  })
}

// 签名函数
function createSign(paramArr, app_secret = '') {
  app_secret = app_secret || zhanfuConfig.app.app_secret;
  let sign = app_secret;
  Object.keys(paramArr).sort().forEach(key => {
    if (key !== '' && paramArr[key] !== '') {
      sign += key + paramArr[key];
    }
  });
  sign += app_secret;
  return md5(sign).toUpperCase()
}

// 组参函数
function createStrParam(paramArr) {
  let strParam = '';
  for (const key in paramArr) {
    if (key !== '' && paramArr[key] !== '') {
      strParam += key + '=' + encodeURIComponent(paramArr[key]) + '&';
    }
  }
  return strParam;
}
module.exports = ruxOpenApi